import 'dart:ui';

import 'package:flutter/material.dart';
// import 'package:flutter_blue/flutter_blue.dart';
//import 'package:flutter_native_image/flutter_native_image.dart';
import 'package:image_picker/image_picker.dart';
import 'package:magic_car/UI/Loading.dart';
import 'package:magic_car/util/HttpHelper.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:toast/toast.dart';
import 'dart:io';

class Qimianinspect extends StatefulWidget {
  final Map param;
  Qimianinspect(this.param);

  @override
  _MyHomePageState createState() => new _MyHomePageState(this.param);
}

class _MyHomePageState extends State<Qimianinspect> {
  List formList;
  final Map param;
  bool select = false;
  String itemid;
  Map currentTest=new Map();
  // FlutterBlue flutterBlue = FlutterBlue.instance;
  // BluetoothDevice device;
  Color Select_Color=Colors.white;
  int selectIndex;
  String bluetoothStatus="连接漆膜仪";
  _MyHomePageState(this.param);
  initState() {
    super.initState();
    formList = [
      {
        "title": '客户姓名',
        'sub_title': '云A00001',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '车牌号',
        'sub_title': '云A00001',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '车牌号',
        'sub_title': '云A00001',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '车牌号',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
    ];
    // _showDialog(2);
  }

  photo(item) async {
    var image = await ImagePicker.pickImage(source: ImageSource.camera);
    if (image == null) return;
    // File _files = await FlutterNativeImage.compressImage(image.path);
    File _files = image;
    Map<String, String> map = new Map();

    HttpHelper.upLoadImage(_files, (data) {
      print('data');
      if (data.containsKey('code')) {
        Toast.show(data['msg'], context);
      } else {
        List tempimg1 =
            item.containsKey("urlArr1") ? item["urlArr1"] : new List();
        List tempimg = new List();
        tempimg.add(data["filename"]);
        tempimg.add(data["url"]);
        tempimg1.add(tempimg);
        setState(() {
          item["urlArr1"] = tempimg1;
        });
      }
    }, params: map);
  }

  Widget buildcontent() {
    List<Widget> tiles = [];
    Widget content;
    List postdata = param["post"];
    itemid = param["id"];
    // print(param);
    // print('传递数值');
    for (var i =0;i<postdata.length;i++) {
      var item = postdata[i];
      TextEditingController textEditingController = TextEditingController();
      double height = 80;
      if (item["mustimg"] == "1") height = 270;
      tiles.add(Padding(
          padding: new EdgeInsets.fromLTRB(0, 1, 0, 0),
          
          child:new GestureDetector(
            onTap: (){
             // print('点击测量项目');
             setState(() {
               currentTest=item;
               selectIndex=i;
               //Select_Color=Colors.grey;
             });
            },
            child:
          Container(
            color: selectIndex==i?Color.fromRGBO(230, 230, 230, 1):Colors.white,
            // height: height,
            child: new Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                Padding(
                    padding: new EdgeInsets.fromLTRB(10, 10, 0, 0),
                    
                    child: new Row(
                      children: <Widget>[
                        new Text(item["name"]),
                        item["mustimg"] == "1"
                            ? Padding(
                                padding: new EdgeInsets.fromLTRB(10, 0, 0, 0),
                                child: new GestureDetector(
                                    onTap: () {
                                      photo(item);
                                    },
                                    child: new Image.asset(
                                      'resource/images/user/cremra.png',
                                      width: 20,
                                      height: 20,
                                      fit: BoxFit.contain,
                                    )))
                            : new Text('')
                      ],
                    )),
                item["item"] == ""
                    ? new TextField(

                        // controller: textEditingController,
                        onChanged: (value) {
                          print(value);
                          setState(() {
                            item['value'] = value;
                          });
                        },
                        decoration: InputDecoration(
                          hintText: item.containsKey("value")
                              ? item['value']
                              : '请填写相关信息',
                          border: OutlineInputBorder(
                            borderSide: BorderSide.none,
                          ),
                        ))
                    : checkBox(item),
               item.containsKey("numerical_value")? testresult(item):new Text(''),
                item.containsKey("urlArr1") ? imgs(item) : new Text('')
              ],
            ),
            // child: new Row(
            //   children: <Widget>[
            //     Expanded(
            //       child: new Padding(
            //           padding: new EdgeInsets.fromLTRB(10, 0, 10, 0),
            //           child: new Text(
            //             item['name'],
            //             style: TextStyle(
            //                 fontSize: 15,
            //                 color: Color.fromRGBO(102, 102, 102, 1)),
            //           )),
            //       flex: 1,
            //     ),
            //     new Padding(
            //         padding: new EdgeInsets.fromLTRB(0, 0, 10, 0),
            //         child: new Text(
            //           item['id'],
            //           style:
            //               TextStyle(fontSize: 15, color: Color.fromRGBO(27, 182, 251, 1)),
            //         )),
            //   ],
          ))));
    }
    content = new Column(
        children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
        //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
        );
    return content;
  }

  //漆膜仪检测的数值
  Widget testresult(item) {
    Widget content;
    List<Widget> tiles = [];
    print(item["testnum"]);
   // int itemnum = int.parse(item["testnum"]);
   int itemnum = item['numerical_value'].length;
    for (var i = 0; i < itemnum; i++) {
      tiles.add(
        Padding(
          padding: new EdgeInsets.fromLTRB(10, 0, 0, 5),
          child: new Container(
            height: 30,
            width: 30,

            decoration: new BoxDecoration(
              border: new Border.all(color: Colors.red, width: 0.0), // 边色与边宽度
              color: Color(0xFF9E9E9E), // 底色
              //        borderRadius: new BorderRadius.circular((20.0)), // 圆角度
              borderRadius:
                  BorderRadius.all(Radius.circular(15.0)), // 也可控件一边圆角大小
            ),

            //color: Colors.red,
            child: new Align(
                alignment: Alignment.center,
                child: new Text(
                 item.containsKey('numerical_value')? item['numerical_value'][i].toString():'0',
                  style: TextStyle(color: Colors.white, fontSize: 10),
                )),
          ),
        ),
      );
    }
    content = new Wrap(spacing: 0, runSpacing: 0, children: tiles);
    return content;
  }

  Widget imgs(item) {
    List<Widget> tiles = [];
    Widget content;

    List items = item["urlArr1"];

    for (var i = 0; i < items.length; i++) {
      List temp1 = items[i] as List;
      tiles.add(Padding(
        padding: new EdgeInsets.fromLTRB(10, 0, 0, 10),
        child: GestureDetector(
            onTap: () {
              print('点击查看图片');
              Navigator.of(context).push(
                NinePicture(items, i),
              );
            },
            child: Image.network(temp1[1], width: 100, height: 100)),
      ));
    }
    content = new Wrap(spacing: 0, runSpacing: 0, children: tiles);
    //content = new Row(children: tiles);

    return content;
  }

  Widget checkBox(item) {
    List<Widget> tiles = [];
    Widget content;

    List<String> items = item["item"].split(',');

    String defaultv = items[0];
    if (select == false) {
      if (item.containsKey("value") == false) {
        item['value'] = defaultv;
      }
    } //设置选项默认值
    for (var i = 0; i < items.length; i++) {
      tiles.add(Padding(
          padding: new EdgeInsets.fromLTRB(10, 0, 0, 0),
          child: SizedBox(
              width: 22,
              child: Radio<String>(
                  //当前Radio的值
                  hoverColor: Color.fromRGBO(200, 200, 200, 1),
                  focusColor: Color.fromRGBO(25, 172, 249, 1),
                  value: items[i],
                  activeColor: Color.fromRGBO(25, 172, 249, 1),
                  groupValue: item['value'],
                  // groupValue: defaultv,
                  onChanged: (value) {
                    setState(() {
                      select = true;
                      // defaultv = value;
                      item['value'] = value;
                    });
                  }))));

      tiles.add(Padding(
          padding: new EdgeInsets.fromLTRB(10, 17, 0, 0),
          child: Text(items[i],
              style: new TextStyle(
                  fontSize: 11, color: Color.fromRGBO(100, 100, 100, 1)))));
    }
    content = new Wrap(spacing: 0, runSpacing: 0, children: tiles);
    //content = new Row(children: tiles);

    return content;
  }

  Widget build(BuildContext context) {
    return new Scaffold(
          appBar: new AppBar(
            title: new Text(param["name"]),
            backgroundColor: Colors.white,
            iconTheme: new IconThemeData(color: Colors.black),
            elevation: 0,
            // backgroundColor: Color.fromRGBO(255, 204, 48, 1),
          ),
          body: new Center(
              child: Container(
                  decoration: new BoxDecoration(
                    //color: Colors.white
                    color: Color.fromRGBO(238, 238, 238, 1),
                  ),
                  child: Stack(
                    children: <Widget>[
                      Align(
                        alignment: Alignment.topCenter,
                        child: Container(
                            color: Colors.white,
                            width: double.infinity,
                            height: param["mustmodel"] == "1" ? 250 : 0,
                            padding: new EdgeInsets.fromLTRB(0, 10, 0, 20),
                            //color: Colors.red,
                            //color: Colors.red,
                            child: Align(
                              alignment: Alignment.topCenter,
                              child: param["mustmodel"] == "1"
                                  ? showProblem()
                                  : new Text(""),
                            )),
                      ),
                      Align(
                        alignment: Alignment.bottomCenter,
                        child: Padding(
                          padding: new EdgeInsets.fromLTRB(0, 0, 0, 0),
                          // child: new Text('连接蓝牙',style: new TextStyle(color:Colors.red))
                          child: 
                          Container(
                            width: double.infinity,
                            color: Color.fromRGBO(27, 182, 251, 1),
                            child:
                          new FlatButton(
                              onPressed: () {
                                connect();
                              },
                              child: new Text(bluetoothStatus,style: TextStyle(color:Colors.white),)),
                        ),
                      )),
                      Align(
                          alignment: Alignment.bottomCenter,
                          child: Padding(
                            padding: new EdgeInsets.fromLTRB(
                                0, param["mustmodel"] == "1" ? 250 : 0, 0, 50),
                            child: new ListView(
                                children: <Widget>[buildcontent()]),
                          )),
                    ],
                  )
                  // Padding(
                  //     padding: new EdgeInsets.fromLTRB(0, 15, 0, 0),
                  //     child: new ListView(
                  //       children: <Widget>[buildcontent()],
                  //     )),
                  )));
    // return WillPopScope(
    //   child: new Scaffold(
    //       appBar: new AppBar(
    //         title: new Text(param["name"]),
    //         backgroundColor: Colors.white,
    //         iconTheme: new IconThemeData(color: Colors.black),
    //         elevation: 0,
    //         // backgroundColor: Color.fromRGBO(255, 204, 48, 1),
    //       ),
    //       body: new Center(
    //           child: Container(
    //               decoration: new BoxDecoration(
    //                 //color: Colors.white
    //                 color: Color.fromRGBO(238, 238, 238, 1),
    //               ),
    //               child: Stack(
    //                 children: <Widget>[
    //                   Align(
    //                     alignment: Alignment.topCenter,
    //                     child: Container(
    //                         color: Colors.white,
    //                         width: double.infinity,
    //                         height: param["mustmodel"] == "1" ? 250 : 0,
    //                         padding: new EdgeInsets.fromLTRB(0, 10, 0, 20),
    //                         //color: Colors.red,
    //                         //color: Colors.red,
    //                         child: Align(
    //                           alignment: Alignment.topCenter,
    //                           child: param["mustmodel"] == "1"
    //                               ? showProblem()
    //                               : new Text(""),
    //                         )),
    //                   ),
    //                   Align(
    //                     alignment: Alignment.bottomCenter,
    //                     child: Padding(
    //                       padding: new EdgeInsets.fromLTRB(0, 0, 0, 0),
    //                       // child: new Text('连接蓝牙',style: new TextStyle(color:Colors.red))
    //                       child: 
    //                       Container(
    //                         width: double.infinity,
    //                         color: Color.fromRGBO(27, 182, 251, 1),
    //                         child:
    //                       new FlatButton(
    //                           onPressed: () {
    //                             connect();
    //                           },
    //                           child: new Text(bluetoothStatus,style: TextStyle(color:Colors.white),)),
    //                     ),
    //                   )),
    //                   Align(
    //                       alignment: Alignment.bottomCenter,
    //                       child: Padding(
    //                         padding: new EdgeInsets.fromLTRB(
    //                             0, param["mustmodel"] == "1" ? 250 : 0, 0, 50),
    //                         child: new ListView(
    //                             children: <Widget>[buildcontent()]),
    //                       )),
    //                 ],
    //               )
    //               // Padding(
    //               //     padding: new EdgeInsets.fromLTRB(0, 15, 0, 0),
    //               //     child: new ListView(
    //               //       children: <Widget>[buildcontent()],
    //               //     )),
    //               ))),
    //   onWillPop: () => willpop(),
    // );
  }

  connect() async {
   // print('连接仪器');
    // context this = new BuildContext();
    // LoadingPage loadpage =new LoadingPage(context);
    // loadpage.show();
  //   if(bluetoothStatus=="断开漆膜仪"){
      
  //  await device.disconnect();
   
  // //  device.discoverServices();
  //  setState(() {
  //   bluetoothStatus="连接漆膜仪";
  // });
  //   }else{
  //     print('连接蓝牙');
  //    // flutterBlue.startScan();
  //   flutterBlue.scan().listen((scanresult) {
      
  //     String deveceName = scanresult.device.name;
  //     if (deveceName.startsWith('LS')) {
  //       device = scanresult.device;
  //       startconnetc();
  //       flutterBlue.stopScan();
  //       //loadpage.close();
  //     } else {
  //       Toast.show('没有找到相关设备', context);
  //       //loadpage.close();
  //     }
  //   });
    
  //   }
  }

  startconnetc() async {
  //   await device.connect();
  //   Toast.show('漆膜仪连接成功', context);
  // // setState(() {
  // //   bluetoothStatus="断开漆膜仪";
  // // });
  //   List<BluetoothService> services = await device.discoverServices();
  //   services.forEach((service) async {
  //     // do something with service
  //     var characteristics = service.characteristics;
  //     for (BluetoothCharacteristic c in characteristics) {
  //       // List<int> value = await c.read();
  //       // print(value);
  //       await c.setNotifyValue(true);
  //       c.value.listen((value) {
  //         print('值发生改变');
  //         print(value is List);
  //         print(value);
  //         //print(value.length);
  //         if (value.length > 0) {
  //           //第一位先转换为16进制
  //           print(value[8].toRadixString(16).toUpperCase());
  //           var hexStr = "";
  //           if (value[9] == 255) {
  //             //负数
  //           } else {
  //             if (value[8] < 10) {
  //               hexStr = '0' +
  //                   value[11].toString() +
  //                   '0' +
  //                   value[10].toString() +
  //                   '0' +
  //                   value[9].toString() +
  //                   '0' +
  //                   value[8].toString();
  //             } else {
  //               var str = value[8].toRadixString(16).toUpperCase();
  //               if(str.length==1){
  //                 str = "0"+str;
  //               }
  //               hexStr = '0' +
  //                   value[11].toString() +
  //                   '0' +
  //                   value[10].toString() +
  //                   '0' +
  //                   value[9].toString() +
  //                   str;
  //             }
  //             print(hexStr);
  //             print('转换结果' + _hexToInt(hexStr).toString());
  //             if(currentTest.containsKey('numerical_value')){
  //               //有这个检测结果数组，从里面添加
  //              // if(currentTest)
  //               List tempArr = currentTest['numerical_value'];
  //               if(tempArr.length==int.parse(currentTest['testnum'])){
  //                 //达到数量之后开始校验数组
                
  //               Toast.show('测量数量达上线，请进行下一项检测', context);
  //               tempArr.sort();
  //               double re = tempArr.last;
  //               List tempList = currentTest['item'].split(',');
  //               if(re<=180){
  //                 currentTest["value"]=tempList[0];
  //               }else if(re<=330){
  //                 currentTest["value"]=tempList[1];
  //               }else if(re>330){
  //                 currentTest["value"]=tempList[2];
  //               }
  //               setState(() {
  //                 currentTest=currentTest;
  //               });
  //               print(tempArr.last);
  //               return;
  //               }
  //               double re = _hexToInt(hexStr)/10;
  //               // if(re>100){
  //               //   print('需要社区小数点');
  //               //   tempArr.add(int.parse(re.toString()));
  //               // }else
  //               tempArr.add(_hexToInt(hexStr)/10);
  //             }else{
  //               currentTest['numerical_value']=[];
  //               currentTest['numerical_value'].add(_hexToInt(hexStr)/10);
  //             }
  //             print(currentTest);
  //             setState(() {
  //               currentTest=currentTest;
  //             });

  //           }
           
  //         }
  //         // do something with new value
  //       });
  //     }
  //   });
  }

//16进制转换成10进制数值
  int _hexToInt(String hex) {
    int val = 0;
    int len = hex.length;
    for (int i = 0; i < len; i++) {
      int hexDigit = hex.codeUnitAt(i);
      if (hexDigit >= 48 && hexDigit <= 57) {
        val += (hexDigit - 48) * (1 << (4 * (len - 1 - i)));
      } else if (hexDigit >= 65 && hexDigit <= 70) {
        // A..F
        val += (hexDigit - 55) * (1 << (4 * (len - 1 - i)));
      } else if (hexDigit >= 97 && hexDigit <= 102) {
        // a..f
        val += (hexDigit - 87) * (1 << (4 * (len - 1 - i)));
      } else {
        throw new FormatException("Invalid hexadecimal value");
      }
    }
    return val;
  }

  //异常图片
  Widget showProblem() {
    List<Widget> tiles = [];
    Widget content;
    //每次都要加载这张图片，后续优化
    tiles.add(
      Positioned(
          child: new Image.asset(
        'resource/images/jiance/carmodel2.png',
        //fit:BoxFit.none
        //fit: BoxFit.fi,
      )),
    );

    List postData = param["post"];
    for (var item in postData) {
      List<String> items = item["item"].split(',');

      var id = item["id"];
     // print(id);
      if (item.containsKey("value")) {
        if (items[0] != item["value"]) {
          //有异常情况
          String urls =
              'resource/images/jiance/model/qimian/' + id.toString() + '.png';
          File imgs = File(urls);
          var dir_bool = imgs.exists();
          // print(dir_bool);
          // print(urls);
          tiles.add(
            Positioned(
                //     child: new Image.asset(
                //   'resource/images/jiance/xlgx.png'
                //   //fit:BoxFit.none
                //   //fit: BoxFit.fi,
                // )
                child: new Image.asset(urls
                    //fit:BoxFit.none
                    //fit: BoxFit.fi,
                    )),
          );
        }
      }
    }
    content = new Stack(children: tiles);
    return content;
  }

  Future<bool> willpop() {
    _showDialog(1);
    return Future.value(false);
  }

  _showDialog(type) {
    var title = "";
    if (type == 1) {
      title = "此项是否已经检测完毕?";
    } else {
      title = "是否需要连接蓝牙检测?";
    }
    showDialog<Null>(
      context: this.context,
      builder: (BuildContext context) {
        return new AlertDialog(
            title: Text('提示!'),
            content: new Text(title),
            actions: <Widget>[
              new FlatButton(
                  onPressed: () {
                    Navigator.of(this.context).pop();
                    // Navigator.pop(context);
                  },
                  child:
                      new Text('否', style: new TextStyle(color: Colors.red))),
              new FlatButton(
                  onPressed: () {
                    Navigator.of(this.context).pop();
                   // sleep(Duration(seconds: 1));
                    if (type == 2) {
                      connect();
                    } else {
                     // device.disconnect();//断开漆膜仪连接
                      Navigator.pop(context);
                    }
                  },
                  child: new Text(
                    '是',
                    style: new TextStyle(color: Colors.black),
                  ))
            ]);
      },
    );
  }
}

class NinePicture<T> extends PopupRoute<T> {
  final String barrierLabel;
  final List picList;
  final int index;
  int startX;
  int endX;

  NinePicture(this.picList, this.index, {this.barrierLabel});

  @override
  Duration get transitionDuration => Duration(milliseconds: 2000);

  @override
  @override
  Color get barrierColor => Colors.black54;

  @override
  bool get barrierDismissible => true;

  AnimationController _animationController;

  @override
  AnimationController createAnimationController() {
    assert(_animationController == null);
    _animationController =
        BottomSheet.createAnimationController(navigator.overlay);
    return _animationController;
  }

  @override
  Widget buildPage(BuildContext context, Animation<double> animation,
      Animation<double> secondaryAnimation) {
    return MediaQuery.removePadding(
      removeTop: true,
      context: context,
      child: GestureDetector(
        child: AnimatedBuilder(
          animation: animation,
          builder: (BuildContext context, Widget child) => GestureDetector(
            onTap: () {
              Navigator.pop(context);
            },
            child: _PictureWidget(picList, index),
          ),
        ),
      ),
    );
  }
}

class _PictureWidget extends StatefulWidget {
  final List picList;
  final int index;

  _PictureWidget(this.picList, this.index);

  @override
  State createState() {
    return _PictureWidgetState();
  }
}

class _PictureWidgetState extends State<_PictureWidget> {
  int startX = 0;
  int endX = 0;
  int index = 0;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    index = widget.index;
  }

  @override
  Widget build(BuildContext context) {
    return new Material(
      color: Colors.transparent,
      child: new Container(
        width: double.infinity,
        child: Stack(
          children: <Widget>[
            GestureDetector(
              child: Center(
                child: CachedNetworkImage(
                  imageUrl: widget.picList[index][1],
                  fit: BoxFit.cover,
                ),
              ),
              onHorizontalDragDown: (detail) {
                startX = detail.globalPosition.dx.toInt();
              },
              onHorizontalDragUpdate: (detail) {
                endX = detail.globalPosition.dx.toInt();
              },
              onHorizontalDragEnd: (detail) {
                _getIndex(endX - startX);
                setState(() {});
              },
              onHorizontalDragCancel: () {},
            ),
            Align(
              alignment: Alignment.bottomCenter,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: List.generate(
                  widget.picList.length,
                  (i) => GestureDetector(
                    child: CircleAvatar(
                      foregroundColor: Theme.of(context).primaryColor,
                      radius: 8.0,
                      backgroundColor: index == i
                          ? Theme.of(context).primaryColor
                          : Colors.white,
                    ),
                    onTap: () {
                      setState(() {
                        startX = endX = 0;
                        index = i;
                      });
                    },
                  ),
                ).toList(),
              ),
            )
          ],
        ),
        alignment: Alignment.center,
      ),
    );
  }

  void _getIndex(int delta) {
    if (delta > 50) {
      setState(() {
        index--;
        index = index.clamp(0, widget.picList.length - 1);
      });
    } else if (delta < 50) {
      setState(() {
        index++;
        index = index.clamp(0, widget.picList.length - 1);
      });
    }
  }
}
